package com.borderbears.backend.media;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Logger;

import javax.swing.tree.TreeModel;

import nanoxml.XMLElement;
import nanoxml.XMLParseException;

import com.borderbears.backend.util.Config;
import com.borderbears.backend.util.Const;

public class MediaManager implements Const {
	private final Logger log = Logger.getLogger(getClass().getName());

	private static MediaManager instance;

	private final MediaTreeModel xmlTreeModel = new MediaTreeModel();

	public XMLElement loadXMLData() {

		final String mediaURL = Config.getConfig().get(CONF_MEDIAURL, "");

		try {
			final URL url = new URL(mediaURL);

			final InputStreamReader isr = new InputStreamReader(url
					.openStream());
			final XMLElement xml = new XMLElement();
			xml.parseFromReader(isr);
			log.info("XML parsed.");
			return xml;
		} catch (final MalformedURLException e) {
			log.warning("URL was malformed: " + mediaURL);
		} catch (final XMLParseException e) {
			log.warning("Error parsing XML:\n" + e.getMessage());
		} catch (final IOException e) {
			log.warning("Error connecting to: " + mediaURL);
		}

		return null;
	}

	public void setData(final XMLElement xml) {
		xml.setName("directory");
		xmlTreeModel.setRoot(new MediaNode(xml));
	}

	public TreeModel getTreeModel() {
		return xmlTreeModel;
	}

	public MediaType detectMediaType(final MediaNode n) {
		if ((null != n.getURL())
				&& n.getURL().toString().toLowerCase().endsWith(".jpg")) {
			return MediaType.IMAGE;
		}
		return MediaType.FILE;
	}

	public static MediaManager getInstance() {
		if (null == instance) {
			instance = new MediaManager();
		}
		return instance;
	}

}
